﻿using System;
using System.IO;
using System.Xml;
using System.Windows.Forms;

namespace ZplToWpl
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            _zplFolder.Text = Properties.Settings.Default.ZplFolder;
            _wplFolder.Text = Properties.Settings.Default.WplFolder;
            _backup.Checked = Properties.Settings.Default.BackupExistingPlaylists;

            base.OnLoad(e);
        }

        protected override void OnClosed(EventArgs e)
        {
            Properties.Settings.Default.ZplFolder = _zplFolder.Text;
            Properties.Settings.Default.WplFolder = _wplFolder.Text;
            Properties.Settings.Default.BackupExistingPlaylists = _backup.Checked;
            Properties.Settings.Default.Save();

            base.OnClosed(e);
        }

        private void _zplFolder_TextChanged(object sender, EventArgs e)
        {
            RefreshConvertButton();
        }

        private void _wplFolder_TextChanged(object sender, EventArgs e)
        {
            RefreshConvertButton();
        }
        
        private void RefreshConvertButton()
        {
            _convert.Enabled = _zplFolder.Text != string.Empty && _wplFolder.Text != string.Empty &&
                Directory.Exists(_zplFolder.Text) && Directory.Exists(_wplFolder.Text);
        }

        private void _zplBrowse_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog dlg = new FolderBrowserDialog())
            {
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    _zplFolder.Text = dlg.SelectedPath;

                    if (_wplFolder.Text == string.Empty)
                        _wplFolder.Text = dlg.SelectedPath;
                }
            }
        }

        private void _wplBrowse_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog dlg = new FolderBrowserDialog())
            {
                if (dlg.ShowDialog() == DialogResult.OK)
                    _wplFolder.Text = dlg.SelectedPath;
            }
        }

        private void _convert_Click(object sender, EventArgs e)
        {
            _output.Clear();

            string[] zplFiles;

            try
            {
                zplFiles = Directory.GetFiles(_zplFolder.Text, "*.zpl", SearchOption.TopDirectoryOnly);
            }
            catch (Exception ex)
            {
                Log(string.Format("Error opening folder '{0}'. {1}", _zplFolder.Text, ex.Message));
                return;
            }

            foreach (string zplFile in zplFiles)
            {
                XmlDocument zplDoc = new XmlDocument();

                try
                {
                    zplDoc.Load(zplFile);
                }
                catch (Exception ex)
                {
                    Log(string.Format("Error opening file '{0}'. {1}", Path.GetFileName(zplFile), ex.Message));
                    continue;
                }

                XmlDocument wplDoc = new XmlDocument();
                
                wplDoc.LoadXml("<?wpl version=\"1.0\"?><smil><head><title/></head><body><seq/></body></smil>");

                XmlElement zplTitleElem = (XmlElement)zplDoc.SelectSingleNode("/smil/head/title");
                XmlElement wplTitleElem = (XmlElement)wplDoc.SelectSingleNode("/smil/head/title");

                if (zplTitleElem != null)
                    wplTitleElem.InnerText = zplTitleElem != null ? zplTitleElem.InnerText : Path.GetFileNameWithoutExtension(zplFile);

                XmlElement wplSeqElem = (XmlElement)wplDoc.SelectSingleNode("smil/body/seq");

                int missingSongs = 0;

                foreach (XmlElement zplMediaElem in zplDoc.SelectNodes("smil/body/seq/media"))
                {
                    string source = zplMediaElem.GetAttribute("src");

                    if (source != string.Empty && File.Exists(source))
                    {
                        XmlElement wplMediaElem = wplDoc.CreateElement("media");
                        wplMediaElem.SetAttribute("src", source);
                        wplSeqElem.AppendChild(wplMediaElem);
                    }
                    else
                    {
                        missingSongs++;
                    }                    
                }

                string wplFile = Path.Combine(_wplFolder.Text, Path.ChangeExtension(Path.GetFileName(zplFile), "wpl"));

                try
                {
                    if (_backup.Checked && File.Exists(wplFile))
                        File.Copy(wplFile, wplFile + ".backup", true);
                    
                    wplDoc.Save(wplFile);
                }
                catch (Exception ex)
                {
                    Log(string.Format("Error saving file '{0}'. {1}", wplFile, ex.Message));
                    continue;
                }
                if (missingSongs == 0)
                    Log(string.Format("Converted '{0}'.", Path.GetFileName(zplFile)));
                else
                    Log(string.Format("Converted '{0}'. Removed {1} missing song(s).", Path.GetFileName(zplFile), missingSongs));
            }

            _output.AppendText("Done.");
        }

        private void Log(string msg)
        {
            _output.AppendText(string.Concat(msg, Environment.NewLine));
        }

        private void _close_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
